import os
import tkinter as tk
from tkinter import ttk, messagebox
import ast  # 使用ast模块安全地解析JSON文件

script_dir = os.path.dirname(os.path.abspath(__file__))
books_path = os.path.join(script_dir, 'books.json')
students_path = os.path.join(script_dir, 'students.json')

def load_json_file(filepath):
    """不使用json模块加载JSON文件"""
    try:
        with open(filepath, 'r', encoding='utf-8') as f:
            content = f.read()
            return ast.literal_eval(content)  # 安全地评估字符串内容
    except FileNotFoundError:
        messagebox.showerror("错误", f"无法找到文件: {filepath}")
        raise
    except Exception as e:
        messagebox.showerror("错误", f"解析文件出错: {e}")
        raise

# 加载数据
try:
    books_data = load_json_file(books_path)
    students_data = load_json_file(students_path)
except Exception as e:
    messagebox.showerror("错误", f"数据加载失败: {e}")
    raise

library_data = {
    "books": books_data["books"],
    "students": []
}

for student in students_data["students"]:
    library_data["students"].append({
        "id": student["username"],
        "name": student["fullName"],
        "age": student["age"],
        "school": student["school"],
        "interests": student["interests"],
        "relations": student["relations"],
        "followed_courses": student["followed_courses"],
        "borrowed_books": [],
        "credit_points": 3,
        "waiting_list": []
    })

class LibraryUI:
    def __init__(self, root):
        self.root = root
        self.root.title("大学图书馆管理系统")
        self.root.geometry("1000x700")
        
        # 初始化回调方法
        self.view_student_details = None
        self.refresh_students = None
        self.view_book_details = None
        self.refresh_books = None
        self.search_books = None
        self.borrow_book = None
        self.return_book = None
        self.reserve_book = None
        self.report_lost = None
        self.refresh_stats = None
        
        self.create_widgets()
    
    def create_widgets(self):
        self.notebook = ttk.Notebook(self.root)
        
        # 学生管理标签页
        self.student_frame = ttk.Frame(self.notebook)
        self.create_student_tab()
        
        # 图书管理标签页
        self.book_frame = ttk.Frame(self.notebook)
        self.create_book_tab()
        
        # 借阅管理标签页
        self.borrow_frame = ttk.Frame(self.notebook)
        self.create_borrow_tab()
        
        # 统计标签页
        self.stats_frame = ttk.Frame(self.notebook)
        self.create_stats_tab()
        
        self.notebook.add(self.student_frame, text="学生管理")
        self.notebook.add(self.book_frame, text="图书管理")
        self.notebook.add(self.borrow_frame, text="借阅管理")
        self.notebook.add(self.stats_frame, text="统计信息")
        self.notebook.pack(expand=True, fill="both")
    
    def create_student_tab(self):
        self.student_tree = ttk.Treeview(self.student_frame, columns=("User name", "Name", "Age", "Borrowed", "Credit"), show="headings")
        self.student_tree.heading("User name", text="用户名")
        self.student_tree.heading("Name", text="姓名")
        self.student_tree.heading("Age", text="年龄")
        self.student_tree.heading("Borrowed", text="已借数量")
        self.student_tree.heading("Credit", text="信用积分")
        self.student_tree.pack(fill="both", expand=True, padx=10, pady=10)
        
        btn_frame = ttk.Frame(self.student_frame)
        ttk.Button(btn_frame, text="查看详情", command=self._safe_callback("view_student_details")).pack(side="left", padx=5)
        ttk.Button(btn_frame, text="刷新列表", command=self._safe_callback("refresh_students")).pack(side="left", padx=5)
        btn_frame.pack(pady=10)
    
    def create_book_tab(self):
        search_frame = ttk.Frame(self.book_frame)
        ttk.Label(search_frame, text="搜索:").pack(side="left")
        self.book_search_entry = ttk.Entry(search_frame, width=40)
        self.book_search_entry.pack(side="left", padx=5)
        ttk.Button(search_frame, text="搜索", command=self._safe_callback("search_books")).pack(side="left", padx=5)
        search_frame.pack(pady=10)
        
        option_frame = ttk.Frame(self.book_frame)
        self.search_option = tk.StringVar(value="title")
        ttk.Radiobutton(option_frame, text="书名", variable=self.search_option, value="title").pack(side="left")
        ttk.Radiobutton(option_frame, text="作者", variable=self.search_option, value="authors").pack(side="left")
        ttk.Radiobutton(option_frame, text="年份", variable=self.search_option, value="year").pack(side="left")
        option_frame.pack()
                
        self.book_tree = ttk.Treeview(self.book_frame, columns=("Title", "Authors", "Year", "Available"), show="headings")
        self.book_tree.heading("Title", text="书名")
        self.book_tree.heading("Authors", text="作者")
        self.book_tree.heading("Year", text="年份")
        self.book_tree.heading("Available", text="可借数量")
        self.book_tree.column("Title", width=250, anchor="w")
        self.book_tree.column("Authors", width=300, anchor="w")
        self.book_tree.column("Year", width=80, anchor="center")
        self.book_tree.column("Available", width=100, anchor="center")
        self.book_tree.pack(fill="both", expand=True, padx=10, pady=10)
        
        btn_frame = ttk.Frame(self.book_frame)
        ttk.Button(btn_frame, text="查看详情", command=self._safe_callback("view_book_details")).pack(side="left", padx=5)
        ttk.Button(btn_frame, text="刷新列表", command=self._safe_callback("refresh_books")).pack(side="left", padx=5)
        btn_frame.pack(pady=10)

    def create_borrow_tab(self):
        borrow_frame = ttk.LabelFrame(self.borrow_frame, text="借书")
        ttk.Label(borrow_frame, text="用户名:").grid(row=0, column=0, padx=5, pady=5)
        self.borrow_student_entry = ttk.Entry(borrow_frame)
        self.borrow_student_entry.grid(row=0, column=1, padx=5, pady=5)
        
        ttk.Label(borrow_frame, text="图书名称:").grid(row=1, column=0, padx=5, pady=5)
        self.borrow_book_entry = ttk.Entry(borrow_frame)
        self.borrow_book_entry.grid(row=1, column=1, padx=5, pady=5)
        
        ttk.Button(borrow_frame, text="借书", command=self._safe_callback("borrow_book")).grid(row=2, column=0, columnspan=2, pady=10)
        borrow_frame.pack(fill="x", padx=10, pady=10)
        
        return_frame = ttk.LabelFrame(self.borrow_frame, text="还书")
        ttk.Label(return_frame, text="用户名:").grid(row=0, column=0, padx=5, pady=5)
        self.return_student_entry = ttk.Entry(return_frame)
        self.return_student_entry.grid(row=0, column=1, padx=5, pady=5)
        
        ttk.Label(return_frame, text="图书名称:").grid(row=1, column=0, padx=5, pady=5)
        self.return_book_entry = ttk.Entry(return_frame)
        self.return_book_entry.grid(row=1, column=1, padx=5, pady=5)
        
        ttk.Button(return_frame, text="还书", command=self._safe_callback("return_book")).grid(row=2, column=0, columnspan=2, pady=10)
        return_frame.pack(fill="x", padx=10, pady=10)
        
        reserve_frame = ttk.LabelFrame(self.borrow_frame, text="预约")
        ttk.Label(reserve_frame, text="用户名:").grid(row=0, column=0, padx=5, pady=5)
        self.reserve_student_entry = ttk.Entry(reserve_frame)
        self.reserve_student_entry.grid(row=0, column=1, padx=5, pady=5)
        
        ttk.Label(reserve_frame, text="图书名称:").grid(row=1, column=0, padx=5, pady=5)
        self.reserve_book_entry = ttk.Entry(reserve_frame)
        self.reserve_book_entry.grid(row=1, column=1, padx=5, pady=5)
        
        ttk.Button(reserve_frame, text="加入等候列表", command=self._safe_callback("reserve_book")).grid(row=2, column=0, columnspan=2, pady=10)
        reserve_frame.pack(fill="x", padx=10, pady=10)
        
        lost_frame = ttk.LabelFrame(self.borrow_frame, text="报告遗失")
        ttk.Label(lost_frame, text="用户名:").grid(row=0, column=0, padx=5, pady=5)
        self.lost_student_entry = ttk.Entry(lost_frame)
        self.lost_student_entry.grid(row=0, column=1, padx=5, pady=5)
        
        ttk.Label(lost_frame, text="图书名称:").grid(row=1, column=0, padx=5, pady=5)
        self.lost_book_entry = ttk.Entry(lost_frame)
        self.lost_book_entry.grid(row=1, column=1, padx=5, pady=5)
        
        ttk.Button(lost_frame, text="报告遗失", command=self._safe_callback("report_lost")).grid(row=2, column=0, columnspan=2, pady=10)
        lost_frame.pack(fill="x", padx=10, pady=10)
    
    def create_stats_tab(self):
        popular_frame = ttk.LabelFrame(self.stats_frame, text="最受欢迎图书")
        self.popular_list = tk.Listbox(popular_frame, height=10)
        self.popular_list.pack(fill="both", expand=True, padx=10, pady=10)
        popular_frame.pack(fill="both", expand=True, padx=10, pady=10)
        
        ttk.Button(self.stats_frame, text="刷新统计", command=self._safe_callback("refresh_stats")).pack(pady=10)
    
    def _safe_callback(self, method_name):
        """安全回调方法"""
        def wrapper():
            method = getattr(self, method_name, None)
            if method:
                method()
        return wrapper